type LessonProgressStatus = 'NOT_STARTED' | 'IN_PROGRESS' | 'COMPLETED'

interface LessonProgressEntry {
  status: LessonProgressStatus
  percent: number
  updatedAt: number
}

type LessonProgressStorageValue = LessonProgressEntry | LessonProgressStatus

const STORAGE_KEY = 'sunlake-course-progress'

interface CourseProgressRecord {
  [courseId: string]: Record<string, LessonProgressStorageValue>
}

const clampPercent = (value: number) => {
  if (!Number.isFinite(value)) return 0
  if (value < 0) return 0
  if (value > 100) return 100
  return Math.round(value)
}

const resolveStatusFromPercent = (percent: number): LessonProgressStatus => {
  if (percent >= 100) return 'COMPLETED'
  if (percent > 0) return 'IN_PROGRESS'
  return 'NOT_STARTED'
}

const normalizeEntry = (value: LessonProgressStorageValue): LessonProgressEntry => {
  if (typeof value === 'string') {
    const status = value
    const percent = status === 'COMPLETED' ? 100 : 0
    return { status, percent, updatedAt: Date.now() }
  }
  const percent = clampPercent(value.percent ?? 0)
  const status = value.status ?? resolveStatusFromPercent(percent)
  return {
    status: percent >= 100 ? 'COMPLETED' : status,
    percent: percent >= 100 ? 100 : percent,
    updatedAt: value.updatedAt ?? Date.now(),
  }
}

const normalizeCourseProgress = (
  record: Record<string, LessonProgressStorageValue> | undefined,
): Record<string, LessonProgressEntry> => {
  if (!record) return {}
  const normalized: Record<string, LessonProgressEntry> = {}
  for (const [lessonId, value] of Object.entries(record)) {
    normalized[lessonId] = normalizeEntry(value)
  }
  return normalized
}

const readProgress = (): CourseProgressRecord => {
  if (typeof window === 'undefined') {
    return {}
  }
  try {
    const raw = window.localStorage.getItem(STORAGE_KEY)
    return raw ? (JSON.parse(raw) as CourseProgressRecord) : {}
  } catch (error) {
    console.warn('读取课程进度失败', error)
    return {}
  }
}

const writeProgress = (data: CourseProgressRecord) => {
  if (typeof window === 'undefined') {
    return
  }
  try {
    window.localStorage.setItem(STORAGE_KEY, JSON.stringify(data))
  } catch (error) {
    console.warn('写入课程进度失败', error)
  }
}

export const getLessonProgress = (courseId: string): Record<string, LessonProgressEntry> => {
  const progress = readProgress()
  return normalizeCourseProgress(progress[courseId])
}

export const setLessonProgress = (
  courseId: string,
  lessonId: string,
  patch: Partial<Omit<LessonProgressEntry, 'updatedAt'>>,
): LessonProgressEntry => {
  const progress = readProgress()
  const courseProgress = normalizeCourseProgress(progress[courseId])
  const existing = courseProgress[lessonId] ?? {
    status: 'NOT_STARTED' as LessonProgressStatus,
    percent: 0,
    updatedAt: Date.now(),
  }

  const nextPercent = clampPercent(patch.percent ?? existing.percent ?? 0)
  const requestedStatus = patch.status ?? existing.status
  const nextStatus = patch.status
    ? patch.status
    : nextPercent >= 100
    ? 'COMPLETED'
    : requestedStatus === 'NOT_STARTED' && nextPercent > 0
    ? 'IN_PROGRESS'
    : requestedStatus

  const nextEntry: LessonProgressEntry = {
    status: nextStatus === 'COMPLETED' || nextPercent >= 100 ? 'COMPLETED' : nextStatus,
    percent: nextStatus === 'COMPLETED' || nextPercent >= 100 ? 100 : nextPercent,
    updatedAt: Date.now(),
  }

  const nextCourseProgress: Record<string, LessonProgressEntry> = {
    ...courseProgress,
    [lessonId]: nextEntry,
  }

  progress[courseId] = nextCourseProgress
  writeProgress(progress)

  return nextEntry
}

export type { LessonProgressEntry, LessonProgressStatus }
